<template>
  <div class="pdf-npm">
    <div id="pdf-container">
    </div>
  </div>
</template>
<script>
let PDFJS = require('pdfjs-dist')
PDFJS.GlobalWorkerOptions.workerSrc = require('pdfjs-dist/build/pdf.worker.entry.js')

export default {
  name: 'PdfNpm',
  data() {
    return {
      // pdfurl: 'https://cdn.shhzcj.com/uploads/adInfo/6377279ac56d2.pdf',
      pdfurl:
        'https://chcms.xinxinqushi.com/wxhelp/6cbe14c7-d1c3-460a-aa8d-94056584d2c31672999809371.pdf',
    }
  },
  methods: {
    async loadPdfDocument(url) {
      const loadingTask = PDFJS.getDocument(url)
      const pdf = await loadingTask.promise

      // 获取页面总数
      const numPages = pdf.numPages

      const container = document.getElementById('pdf-container')
      const containerWidth = container.clientWidth

      // 加载并显示每一页
      for (let i = 1; i <= numPages; i++) {
        const page = await pdf.getPage(i)

        const viewport = page.getViewport({ scale: 1 })
        const scale = containerWidth / viewport.width

        const scaledViewport = page.getViewport({ scale })

        // 准备 canvas 元素
        const canvas = document.createElement('canvas')
        const context = canvas.getContext('2d')
        canvas.height = scaledViewport.height
        canvas.width = scaledViewport.width
        container.appendChild(canvas)

        // 渲染 PDF 页面到 canvas
        const renderContext = {
          canvasContext: context,
          viewport: scaledViewport,
        }
        await page.render(renderContext).promise
      }
    },
  },
  created() {},
  mounted() {
    this.loadPdfDocument(this.pdfurl)
    // this.loadPdfDocument(
    //   'https://chcms.xinxinqushi.com/wxhelp/6cbe14c7-d1c3-460a-aa8d-94056584d2c31672999809371.pdf'
    // )
    window.addEventListener('resize', () => {
      const container = document.getElementById('pdf-container')
      container.innerHTML = ''
      this.loadPdfDocument(this.pdfurl)
    })
  },
  computed: {},
}
</script>
<style lang="scss">
body,
html {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  overflow: auto;
}
#pdf-container {
  width: 100%;
  height: 100%;
}
</style>
